package com.atguigu.gulimall.product.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName CacheConfig
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/8
 * @Version 1.0
 */
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching  //开启缓存注解
public class CacheConfig {

    /**
     * 配置了RedisCacheConfiguration后，在application.properties配置文件的配置就会失效
     * 这时候就要使用@EnableConfigurationProperties去绑定CacheProperties.class，获取CacheProperties对象，从而获取propertiesRedis对象
     * 在将CacheProperties.class设置进去
     * @param cacheProperties
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //所有Redis缓存的序列化类型都是实现RedisSerializer接口
        //指定key的String类型的序列化类型
        config=config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //指定value的序列化类型是支持泛型的Json格式
        config=config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
        CacheProperties.Redis propertiesRedis = cacheProperties.getRedis();
        //将CacheProperties.class值设置到配置中，这样CacheProperties.class的配置才会生效
        //设置存活时间
        if(propertiesRedis.getTimeToLive() != null){
            config=config.entryTtl(propertiesRedis.getTimeToLive());
        }
        //设置key前缀
        if(propertiesRedis.getKeyPrefix() != null){
            config=config.prefixKeysWith(propertiesRedis.getKeyPrefix());
        }
        //设置是否存储null，用于防止缓存穿透
        if(!propertiesRedis.isCacheNullValues()){
            config=config.disableCachingNullValues();
        }
        //设置是否使用key前缀
        if(!propertiesRedis.isUseKeyPrefix()){
            config=config.disableKeyPrefix();
        }


        return config;
    }
}
